﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using System.IO;
using Orchard.ContentManagement.Aspects;
using Orchard.ContentManagement;
using Newtonsoft.Json;
using Orchard.Mvc;
using Orchard;
using System.Xml.Linq;
using Orchard.Themes;
using Orchard.Security;
using Orchard.Security.Permissions;
using System.Net;
using Orchard.Core.Contents.Settings;
using System.Linq.Expressions;
using System.Collections;

namespace Piedone.WebServices.Controllers
{
    public class ContentsController : Controller
    {
        private readonly IOrchardServices _orchardServices;
        private readonly IContentManager _contentManager;
        private readonly IAuthorizer _authorizer;
        private readonly IHttpContextAccessor _httpContextAccessor;

        public ContentsController(
            IOrchardServices orchardServices,
            IHttpContextAccessor httpContextAccessor)
        {
            _orchardServices = orchardServices;
            _contentManager = orchardServices.ContentManager;
            _authorizer = orchardServices.Authorizer;
            _httpContextAccessor = httpContextAccessor;
        }

        [ServiceAction]
        public ActionResult Index(int id, int top = 2)
        {
            return new HttpUnauthorizedResult("kk");
            var response = new Dictionary<string, Dictionary<string, string>>();
            response["error"] = new Dictionary<string, string>
            {
                {"message", "kkk"}
            };

            return Json(response, JsonRequestBehavior.AllowGet);
            return new JsonResult { Data = GetSerializedItem(id), JsonRequestBehavior = JsonRequestBehavior.AllowGet };
        }

        [HttpPut, ActionName("Index"), ServiceAction]
        public JsonResult IndexPut(int id = 0)
        {
            var inputStream = _httpContextAccessor.Current().Request.InputStream;
            inputStream.Seek(0, SeekOrigin.Begin);
            using (var sr = new StreamReader(inputStream))
            {
                var putData = sr.ReadToEnd();

                // Logic from Orchard.Recipes.RecipeHandlers.DataRecipeHandler
                var xNode = JsonConvert.DeserializeXNode(putData);
                var element = xNode.Element(xNode.Root.Name);

                var importContentSession = new ImportContentSession(_contentManager);

                string identity;
                ContentItem item;
                var elementId = element.Attribute("Id");
                if (id != 0)
                {
                    item = _contentManager.Get(id, VersionOptions.AllVersions);
                    identity = _contentManager.GetItemMetadata(item).Identity.ToString();
                }
                else if (elementId != null)
                {
                    identity = elementId.Value;
                    item = importContentSession.Get(identity);
                }
                else
                {
                    // Items should have an identity
                    return null;
                }

                if (item == null)
                {
                    item = _contentManager.New(element.Name.LocalName);
                }
                else
                {
                    item = _contentManager.Get(item.Id, VersionOptions.AllVersions);
                }

                if (!Authorize(Orchard.Core.Contents.Permissions.EditContent, item))
                {
                    // Return authorization error
                    return null;
                }

                importContentSession.Set(identity, item.ContentType);
                _contentManager.Import(element, importContentSession);
                if (item.Has<IPublishingControlAspect>() || item.TypeDefinition.Settings.GetModel<ContentTypeSettings>().Draftable)
                {
                    _contentManager.Publish(item);
                }

                return new JsonResult { Data = GetSerializedItem(item.Id) };
            }
        }

        private string GetSerializedItem(int id)
        {
            var item = _contentManager.Get(id);

            if (item == null) return "";

            var doc = new XDocument();
            var element = _contentManager.Export(item);
            element.SetAttributeValue("NumericId", id);
            doc.Add(element);
            return JsonConvert.SerializeXNode(doc);
        }

        private bool Authorize(Permission permission, IContent content)
        {
            if (_authorizer.Authorize(permission, content)) return true;

            _httpContextAccessor.Current().Response.StatusCode = (int)HttpStatusCode.Unauthorized;
            return false;
        }


        //[Themed]
        public JsonResult Test()
        {
            _httpContextAccessor.Current().Response.StatusCode = (int)HttpStatusCode.Unauthorized;
            return Json("jaj", JsonRequestBehavior.AllowGet);
            //return View();
        }
    }
}
